<?php

    ##################################################
    #
    # Copyright (c) 2009 Immanuel192 - ABSoft
    # 7/23/2009: Make smart redirect sync better when works with SEF
    // Bail in case someone has visited us directly, or the Pathos framework is
    // otherwise not initialized.
    if (!defined('EXPONENT')) exit('');

    // Initialize the Exponent Framework
    require_once('exponent.php');

    // Initialize the Sessions Subsystem
    if (!defined('SYS_SESSIONS')) require_once(BASE.'subsystems/sessions.php');

    $lang_act=0;
    $lang_selected = null;
    $langs = exponent_lang_full();
    
    if (exponent_lang_exist($_REQUEST['lid']) == 1)
    {
        exponent_sessions_set('language', $_REQUEST['lid']);
        $lang=exponent_sessions_get('language');
        $lang_act=1;

        foreach ($langs as $k=>$v)
            if ($v['lang_code'] == $_REQUEST['lid'])
            {
                $lang_selected = $v;
                break;
            }
            // find selected lang

            $lang_number=$lang_selected['lang_number'];
    }
    //$url=exponent_flow_get();
    $url = $_SERVER['HTTP_REFERER'];
    if ($url == "")
        $url = exponent_flow_get();
    $last_section = exponent_sessions_get("last_section");

    //echo $url ."<br>";
    //echo "section=".$last_section;

    if ($lang_act == 1)
    {
        if (SEF_URLS == 1)
        { // here we will search for section id
            $find_section=strrpos($url,"/");
            $find_section = substr($url, $find_section+1);
            $temp= $db->selectObject('section','sef_name="'. $find_section.'"');
            if ($temp)
            {
                $findex=1; // fake that $findex > 0
                $last_section = "{$temp->id}";   
            }
        }
        else
        { // not in SEF_URL mode; search normal
            $findex=strpos($url, "section=".$last_section);
        }
        if ($findex > 0 )
        {
            $last_section=exponent_lang_get_number($lang) . substr($last_section,1);
            $temp= $db->selectObject('section','id='. $last_section );
            if ($temp) // check if page exist
            {
                $params = array("section"=> $last_section);
                $url = URL_BASE.exponent_core_makeLink($params);
            }
            else
                $url="/";

        }
        else
        {
            $url="/{$lang_selected['url_prefix']}/";
        }

        // fix URL prefix
        $url = str_replace(URL_FULL.LANG_URL_PREFIX,URL_FULL.$lang_selected['url_prefix'],$url);
    }
    
    echo $url;

    header("Location: {$url}");	
    exit('Changing language...');

?>
